﻿//----------------------------------------------------------------------------------------------------
// The Tick Service is responsible for ticking the GameService, which in turn ticks all other managers
//----------------------------------------------------------------------------------------------------

package HG.Services
{
	import flash.utils.*;

	public class TickService
	{
		var m_owner:Object;
		var m_deltaTime:Number;
		
		var m_intervalHandler:Number;
		
		//----------------------------------------------------------------------------------------------------
		public function TickService(owner:Object, deltaTime:Number)
		{
			m_owner = owner;
	
			SetTicktime(deltaTime);
		}
		//----------------------------------------------------------------------------------------------------
		// SetTickTime allows for dynamic changing of the delay between ticks.
		//----------------------------------------------------------------------------------------------------
		public function SetTicktime(deltaTime:Number)
		{
			m_deltaTime = deltaTime;
			
			clearInterval(m_intervalHandler);
			m_intervalHandler = setInterval(OnExternalTickEvent, m_deltaTime, this);
		}
		
		//----------------------------------------------------------------------------------------------------
		// Stop ends all ticks
		//----------------------------------------------------------------------------------------------------
		public function Stop()
		{
			clearInterval(m_intervalHandler);
		}
		
		//----------------------------------------------------------------------------------------------------
		// OnExternalTickEvent is used in dispatch, it does not register as part of the TickService Class
		//----------------------------------------------------------------------------------------------------
		private function OnExternalTickEvent(eTickService:Object)
		{
			// Call the TickService OnTickEvent function.
			eTickService.OnTickEvent();
		}
		
		//----------------------------------------------------------------------------------------------------
		// OnTickEvent - interal tick call
		//----------------------------------------------------------------------------------------------------
		private function OnTickEvent()
		{
			// Call the owning class OnTick (Should be GameService)
			m_owner.OnTick(m_deltaTime);
		}
		
		//----------------------------------------------------------------------------------------------------
		// TickService singleton manager
		//----------------------------------------------------------------------------------------------------
		static var ms_instance:TickService;
		public static function GetInstance(owner:Object, deltaTime:Number):TickService
		{
			if (!ms_instance)
			{
				ms_instance = new TickService(owner, deltaTime);
			}
			return ms_instance;
		}
		//----------------------------------------------------------------------------------------------------
	}
}